package com.tepth.vehiclemaintenance.mvp.work.detail;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.tepth.vehiclemaintenance.R;
import com.tepth.vehiclemaintenance.adapter.RepairOperatorAdapter;
import com.tepth.vehiclemaintenance.base.BaseBackFragment;
import com.tepth.vehiclemaintenance.bean.DetailDriverRemark;
import com.tepth.vehiclemaintenance.bean.MaintainListWork;
import com.tepth.vehiclemaintenance.config.SpKey;
import com.tepth.vehiclemaintenance.dataprovider.OperatorListProvider;
import com.tepth.vehiclemaintenance.event.SearchResultEvent;
import com.tepth.vehiclemaintenance.event.WorkDetailEvent;
import com.tepth.vehiclemaintenance.tools.SPUtils;
import com.tepth.vehiclemaintenance.ui.view.dialog.DialogDelegate;
import com.tepth.vehiclemaintenance.ui.view.dialog.SweetAlertDialogDelegate;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by zhangyu on 2017/5/15.
 */

public class DetailFragment extends BaseBackFragment implements DetailContract.View {
    private static final String PARAMETER = "ListContentsBean";

    public static DetailFragment newInstance(MaintainListWork.ListContentsBean listContentsBean) {
        DetailFragment fragment = new DetailFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(PARAMETER, listContentsBean);
        fragment.setArguments(bundle);
        return fragment;
    }

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tv_des)
    TextView mTextViewDes;
    @BindView(R.id.recycler_view_tool)
    RecyclerView mRecyclerView;
    @BindView(R.id.recycler_view_manual)
    RecyclerView mRecyclerViewManual;
    private RepairOperatorAdapter operatorAdapter;
    private RepairOperatorAdapter operatorAdapterManual;
    private DetailContract.Presenter mPresenter;
    private MaintainListWork.ListContentsBean mListContentsBean;
    private ArrayList<MaintainListWork.ListContentsBean.ListRemarkBean.OperationBean> mOperationBeanArrayList
            = new ArrayList<>();
    private DialogDelegate mDialogDelegate;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mListContentsBean = (MaintainListWork.ListContentsBean) bundle.getSerializable(PARAMETER);
        }
    }

    @Override
    protected void setPresenter() {
        mPresenter = new DetailPresenter();
        DetailContract.Model model = new DetailModel();
        mPresenter.setVM(this, model);
    }

    @Override
    protected void unbindPresenter() {
        mPresenter.onDestroy();
    }

    @Override
    protected void initView(View view) {
        EventBus.getDefault().register(this);

        mToolbar.setTitle(mListContentsBean.getContentDesc());
        initToolbarNav(mToolbar);
        mTextViewDes.setText(mListContentsBean.getTechnicalRequirement());

        List<MaintainListWork.ListContentsBean.ListRemarkBean> listRemarkBeen = mListContentsBean.getListRemark();
        List<MaintainListWork.ListContentsBean.ListRemarkBean> tempTroubleList = new ArrayList<>();
        List<MaintainListWork.ListContentsBean.ListRemarkBean> tempRemarkList = new ArrayList<>();
        if (listRemarkBeen == null || listRemarkBeen.isEmpty()) {
            tempTroubleList = mListContentsBean.getListTrouble();
            if (tempTroubleList != null) {
                for (MaintainListWork.ListContentsBean.ListRemarkBean b : tempTroubleList) {
                    b.setType(true);
                }
            }
        } else {
            for (MaintainListWork.ListContentsBean.ListRemarkBean bean : listRemarkBeen) {
                if (bean.isType()) {
                    tempTroubleList.add(bean);
                } else {
                    tempRemarkList.add(bean);
                }
            }
        }

        initRecyclerViewTrouble(tempTroubleList);
        initRecyclerViewManual(tempRemarkList);
        mDialogDelegate = new SweetAlertDialogDelegate(_mActivity);
        if (OperatorListProvider.getOperatorList() == null) {
            mPresenter.getOperatorList();
            mDialogDelegate.showProgressDialog(true, "正在加载...");
        }
    }

    private void initRecyclerViewTrouble(List<MaintainListWork.ListContentsBean.ListRemarkBean> list) {

        mRecyclerView.setLayoutManager(new LinearLayoutManager(_mActivity));

        operatorAdapter = new RepairOperatorAdapter(_mActivity,
                list,
                mListContentsBean.getState(), false);
        mRecyclerView.setAdapter(operatorAdapter);
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {

            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                if (view.getId() == R.id.btn_delete) {
                    operatorAdapter.getData().remove(position);
                    adapter.notifyItemRemoved(position);
                    //删除
                    adapter.notifyItemRangeChanged(0, operatorAdapter.getData().size() - position);
                } else if (view.getId() == R.id.iv_add) {
                    MaintainListWork.ListContentsBean.ListRemarkBean troubleContent =
                            (MaintainListWork.ListContentsBean.ListRemarkBean) adapter.getItem(position);
                    troubleContent.setUseCount(troubleContent.getUseCount() + 1);
                    adapter.notifyItemChanged(position, troubleContent);
                } else if (view.getId() == R.id.iv_minus) {
                    MaintainListWork.ListContentsBean.ListRemarkBean troubleContent =
                            (MaintainListWork.ListContentsBean.ListRemarkBean) adapter.getItem(position);
                    if (troubleContent.getUseCount() <= 1) {
                        return;
                    }
                    troubleContent.setUseCount(troubleContent.getUseCount() - 1);
                    adapter.notifyItemChanged(position, troubleContent);
                }
            }
        });
    }

    private void initRecyclerViewManual(List<MaintainListWork.ListContentsBean.ListRemarkBean> list) {
        mRecyclerViewManual.setLayoutManager(new LinearLayoutManager(_mActivity));
        operatorAdapterManual = new RepairOperatorAdapter(_mActivity,
                list,
                mListContentsBean.getState(),
                true);
        mRecyclerViewManual.setAdapter(operatorAdapterManual);
        mRecyclerViewManual.addOnItemTouchListener(new OnItemClickListener() {

            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.btn_delete) {
                    operatorAdapterManual.getData().remove(position);
                    adapter.notifyItemRemoved(position);
                    //删除
                    adapter.notifyItemRangeChanged(0, operatorAdapterManual.getData().size() - position);
                } else if (view.getId() == R.id.iv_add) {
                    MaintainListWork.ListContentsBean.ListRemarkBean troubleContent =
                            (MaintainListWork.ListContentsBean.ListRemarkBean) adapter.getItem(position);
                    troubleContent.setUseCount(troubleContent.getUseCount() + 1);
                    adapter.notifyItemChanged(position, troubleContent);
                } else if (view.getId() == R.id.iv_minus) {
                    MaintainListWork.ListContentsBean.ListRemarkBean troubleContent =
                            (MaintainListWork.ListContentsBean.ListRemarkBean) adapter.getItem(position);
                    if (troubleContent.getUseCount() <= 1) {
                        return;
                    }
                    troubleContent.setUseCount(troubleContent.getUseCount() - 1);
                    adapter.notifyItemChanged(position, troubleContent);
                }
            }
        });
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_maintain_detail, container, false);
    }

    @Override
    public void onNetworkError(String msg) {
        mDialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onError(String msg) {
        mDialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onTokenInvalid(String msg) {
        mDialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public String getAuthKey() {
        return SPUtils.getString(_mActivity, SpKey.KEY_AUTH_KEY, "");
    }

    @Override
    public int getMaintainId() {
        return 0;
    }

    @Override
    public void showMaintainDetail(DetailDriverRemark detailDriverRemark) {

    }

    @Override
    public void showOperatorList(ArrayList<MaintainListWork.ListContentsBean.ListRemarkBean.OperationBean> list) {
        if (list != null) {
            OperatorListProvider.setOperationList(list);
        }
        mDialogDelegate.clearDialog();
    }

    @OnClick(R.id.btn_add)
    public void onAddManual() {
        new ChooseOperatorDialog(_mActivity, OperatorListProvider.getOperatorList()).show();
    }

    @OnClick(R.id.btn_done)
    public void onWorkDone() {
        onReturn(false);
    }

    private void onReturn(boolean isReturn) {
        List<MaintainListWork.ListContentsBean.ListRemarkBean> troubleList = operatorAdapter.getData();
        List<MaintainListWork.ListContentsBean.ListRemarkBean> remarkList = operatorAdapterManual.getData();

        List<MaintainListWork.ListContentsBean.ListRemarkBean> temp = new ArrayList<>();
        if (troubleList != null) {
            temp.addAll(troubleList);
        }
        if (remarkList != null) {
            temp.addAll(remarkList);
        }
        EventBus.getDefault().post(new WorkDetailEvent(temp, isReturn));
        pop();
    }

    @Subscribe
    public void onSearchResult(SearchResultEvent event) {

        int type = event.type;
        MaintainListWork.ListContentsBean.ListRemarkBean.OperationBean operationBean =
                event.operationBean;
        MaintainListWork.ListContentsBean.ListRemarkBean.AccessoryBean accessoryBean =
                event.accessoryBean;
        MaintainListWork.ListContentsBean.ListRemarkBean listRemarkBean =
                new MaintainListWork.ListContentsBean.ListRemarkBean();
        listRemarkBean.setOperation(operationBean);
        if (type == 0) {
            listRemarkBean.setAccessory(accessoryBean);
        } else {
            listRemarkBean.setComponent(accessoryBean);
        }
        listRemarkBean.setUseCount(1);
        listRemarkBean.setChecked(true);
        listRemarkBean.setType(true);
        listRemarkBean.setCanDelete(true);

        operatorAdapterManual.getData().add(listRemarkBean);
        int size = operatorAdapterManual.getData().size();
        operatorAdapterManual.notifyItemInserted(size - 1);
        operatorAdapterManual.notifyItemRangeChanged(size - 1, 1);
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Override
    protected void initToolbarNav(Toolbar toolbar) {
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
                onReturn(true);
            }
        });

    }
}
